package com.itheima.reggie.common;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * springmvc 提供的拦截器
 * 1. 编写一个类，实现HandlerInterceptor
 * 2. 配置拦截器，拦截路径/*
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        //判断用户是否登录（看session中有没有employee），如果登录就放行
        Long employeeId = (Long)request.getSession().getAttribute("employee");
        Long userId = (Long)request.getSession().getAttribute("user");

        if (employeeId != null) {
            //员工登录成功的情况下，将员工的id存入本次线程中ThreadLocal
            BaseContext.setCurrentId(employeeId);
            return true;
        }
        if (userId != null) {
            //员工登录成功的情况下，讲用户的id存入本次线程中ThreadLocal
            BaseContext.setCurrentId(userId);
            return true;
        }
        //表示用户没有登录，告诉前端，本次请求访问未登录，被拒接处理，响应code=0，msg=NOTLOGIN
        String json = JSON.toJSONString(R.error("NOTLOGIN"));
        response.getWriter().write(json);
        return false;
       // log.info("当前线程的id:{}",Thread.currentThread().getId());

}
}
